const _ = require('lodash');
import EcgModule from '@/components/EcgModule';
import { SettingOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';
import highMp3 from '../../../public/mp3/high.mp3';
import middleMp3 from '../../../public/mp3/middle.mp3';
import './index.less';
import { ecgWebsocetData, screenAreaListData } from './mock';
/**
 * productModel 产品型号 Dock => k1  海上120 =》ZCHS-HS120-DCJH-001 便携式Max bxsMax
 */
let timer: any = null;
let setIntervalFun: any = null;
let webSocketSetIntervalFun: any = null;
let sendWsDataInterval: any = null;

export default function DashBoardPage() {
  const [nowTime, setNowTime] = useState('');
  const [screenAreaList, setScreenAreaList] = useState<any>([]); //分区列表
  let socketDataRef: any = useRef();
  const wsRef = useRef<any>(null); // 用于管理WebSocket连接
  // 创建音频元素的引用
  const [alarmLevel, setAlarmLevel] = useState<any>(0);
  const playAlarmintervalRef: any = useRef(null);
  const videoRef: any = useRef(null);

  const initData = async () => {
    // 获取当前时间
    timer = window.setInterval(() => {
      setNowTime(dayjs().format('YYYY/MM/DD HH:mm:ss'));
    }, 1000);
    setScreenAreaList(screenAreaListData);
  };
  const CreateMultipleCon = () => {
    webSocketSetIntervalFun = window.setInterval(() => {
      const data = ecgWebsocetData;
      const targetData = data.map((its: any) => {
        const existingItem = socketDataRef.current?.find(
          (item: any) => item.ip === its.ip,
        );
        const existingWaveform = existingItem?.ecgWaveform || {};
        const newWaveform = its.ecgWaveform || {};
        const mergedWaveform: any = {};

        // 合并所有导联数据
        for (const key in newWaveform) {
          if (
            Array.isArray(existingWaveform[key]) &&
            Array.isArray(newWaveform[key])
          ) {
            mergedWaveform[key] = [
              ...existingWaveform[key],
              ...newWaveform[key],
            ];
          } else {
            mergedWaveform[key] =
              newWaveform[key] || existingWaveform[key] || [];
          }
        }

        // 保留旧数据中可能存在的其他属性
        for (const key in existingWaveform) {
          if (!mergedWaveform[key]) {
            mergedWaveform[key] = existingWaveform[key];
          }
        }
        return {
          ip: its.ip,
          ecgWaveform: mergedWaveform,
          heartRate: its.heartRate
            ? its.heartRate
            : existingItem?.heartRate || '-',
          spo2Value: its.spo2Value
            ? its.spo2Value
            : existingItem?.spo2Value || '-',
          temperature1: its.temperature1
            ? its.temperature1
            : existingItem?.temperature1 || '-',
          temperature2: its.temperature2
            ? its.temperature2
            : existingItem?.temperature2 || '-',
          status: its.status,
          alarms: its.alarms || [],
          maxAlarmLevel: its.maxAlarmLevel, // 最大报警等级
        };
      });
      socketDataRef.current = _.cloneDeep(targetData);
    }, 4000);
  };
  const drawIntervalFun = () => {
    setIntervalFun = window.setInterval(() => {
      let maxAlarmLevelTarget = 0; // 最大报警等级
      // console.log('socketDataRef.current', socketDataRef.current);
      if (socketDataRef.current) {
        const oldSocketData = _.cloneDeep(socketDataRef.current);
        const data = _.cloneDeep(oldSocketData).map((its: any) => {
          for (const key in its.ecgWaveform) {
            if (its.ecgWaveform[key].length <= 2000) {
              its.ecgWaveform[key] = its.ecgWaveform[key].splice(0, 9);
            } else {
              its.ecgWaveform[key] = its.ecgWaveform[key].splice(0, 18);
            }
          }
          return its;
        });
        const targetSocketData = _.cloneDeep(socketDataRef.current).map(
          (itsval: any) => {
            for (const keyval in itsval.ecgWaveform) {
              if (itsval.ecgWaveform[keyval].length <= 2000) {
                itsval.ecgWaveform[keyval].splice(0, 9);
              } else {
                itsval.ecgWaveform[keyval].splice(0, 18);
              }
            }
            return itsval;
          },
        );
        socketDataRef.current = _.cloneDeep(targetSocketData);
        let targetScreenAreaList = _.cloneDeep(screenAreaList);
        for (let i = 0; i < data.length; i++) {
          const targetItem = screenAreaList.find((its: any) => {
            return its?.device?.ip == data[i].ip;
          });
          if (targetItem) {
            const ipIndex = screenAreaList.findIndex((its: any) => {
              return targetItem.id == its.id;
            });
            if (
              ipIndex >= 0 &&
              targetScreenAreaList[ipIndex] &&
              targetScreenAreaList[ipIndex].device
            ) {
              // 心电监护
              if (targetItem.device.type == 1) {
                let tempGain = "2"; // 增益
                let targetEcgYAxisData = [];
                for (const key in data[i].ecgWaveform) {
                  targetEcgYAxisData.push({
                    minY: -1,
                    maxY: 1,
                    canvasInterval: 1,
                    color: '#a6f14c',
                    padding: 5,
                    name: key,
                    ecgYAxisData: data[i].ecgWaveform[key],
                    key: data[i].ip + key,
                    id: data[i].ip,
                    leadNumber: key,
                  });
                }
                targetScreenAreaList[ipIndex].device = {
                  ...targetItem.device,
                  ecgYAxisData: targetEcgYAxisData.slice(0, 2),
                };
                targetScreenAreaList[ipIndex] = {
                  ...targetScreenAreaList[ipIndex],
                  ...data[i],
                  gain: tempGain, // 增益
                  ecgFlag: true,
                };
              }
            }
            if (maxAlarmLevelTarget < data[i].maxAlarmLevel) {
              maxAlarmLevelTarget = data[i].maxAlarmLevel;
            }
          }
        }
        setAlarmLevel(String(maxAlarmLevelTarget));
        setScreenAreaList(_.cloneDeep(targetScreenAreaList));
      }
    }, 80);
  };

  useEffect(() => {
    initData();
    return () => {
      if (timer) {
        window.clearInterval(timer);
      }
      if (setIntervalFun) {
        window.clearInterval(setIntervalFun);
      }
      if (webSocketSetIntervalFun) {
        window.clearInterval(webSocketSetIntervalFun);
      }
    };
  }, []);

  useEffect(() => {
    if (screenAreaList.length > 0) {
      CreateMultipleCon();
      setTimeout(() => {
        drawIntervalFun();
      }, 4000);
    }
  }, [screenAreaList.length]);

  useEffect(() => {
    // 清除旧定时器
    if (alarmLevel == 3 || alarmLevel == 2) {
      if (playAlarmintervalRef.current) {
        clearInterval(playAlarmintervalRef.current);
        playAlarmintervalRef.current = null;
      }
      playAlarmintervalRef.current = setInterval(() => {
        videoRef?.current && videoRef?.current.play();
      }, 10000);
    }
    return () => {
      if (playAlarmintervalRef.current) {
        clearInterval(playAlarmintervalRef.current);
        playAlarmintervalRef.current = null;
      }
    };
  }, [alarmLevel]);

  return (
    <div className="dashboard-wrapper">
      <div className="header">
        <div className="left">
          <div className="active circle-num">1</div>
          <div className="circle-num">2</div>
          <div className="circle-num">3</div>
          <SettingOutlined
            onClick={() => {
              window.open(`/patientMsg`);
            }}
            className="main-system"
          />
        </div>
        <div className="title">中央监护系统</div>
        <div className="right">
          <div className="time">{nowTime}</div>
        </div>
      </div>
      <div className="ecg-show-list">
        {screenAreaList.map((its: any, inx: number) => {
          return (
            <div className="ecg-show-item" key={inx + '_screen' + inx}>
              <EcgModule
                itemData={{ ...its }}
                key={inx + '_screen' + inx + '_ecgModule'}
                onCloseWs={() => {
                  sendWsDataInterval &&
                    window.clearInterval(sendWsDataInterval);
                  wsRef?.current && wsRef.current.close();
                }}
                refreshList={() => window.location.reload()}
              />
            </div>
          );
        })}
      </div>
      <video
        ref={videoRef}
        src={alarmLevel == 3 ? highMp3 : alarmLevel == 2 ? middleMp3 : ''}
        width="0"
        height="0"
        playsInline
        preload="metadata"
        autoPlay
        style={{
          display: 'none',
        }}
      />
    </div>
  );
}
